<%

/*
 * Copyright 2006 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

%>

<%@ page import="java.util.*" %>
<%@ page import="bw.weather.*" %>
<%@ page import="bw.util.TimeDelta" %>
<%@ page import="bw.util.DateFactory" %>

<html>
<head>
<title>weather!</title>
<link rel=STYLESHEET type="text/css" href="style.css">
<link rel="SHORTCUT ICON" href="images/favicon.ico">
<script type="text/javascript" src="include/yui_2.6/yahoo-dom-event.js"></script>
<script type="text/javascript" src="include/yui_2.6/animation-min.js"></script> 
<script type="text/javascript" src="include/yui_2.6/connection-min.js"></script>
<script type="text/javascript" src="include/sidebar.js"></script>
<script>

function handleLocationSelect ( w )
{
  var selectedValue = w.options[ w.selectedIndex ].value;
  if ( selectedValue == 'other' )
  {
    var reg = YAHOO.util.Dom.getRegion( 'otherLoc' );
    var lp = 0 - ( reg.right - reg.left ) - 10 ;

    var myAnim = new YAHOO.util.Anim( 'weatherLocForm' );
    myAnim.attributes.left = { to:lp };
    myAnim.duration = .5;
    myAnim.method = YAHOO.util.Easing.easeBothStrong;
    myAnim.onComplete.subscribe( finishShowOtherLoc );

    myAnim.animate();

    document.getElementById( 'otherLocation' ).focus();
  }
  else if ( selectedValue != '' ) { 
    document.getElementById( 'weatherLocForm' ).submit();
  }
}

function finishShowOtherLoc ()
{
  var o = document.getElementById( 'otherLoc' );

  var reg = YAHOO.util.Dom.getRegion( 'weatherLocForm' );

  var pos = new YAHOO.util.Point( reg.right + 10, reg.top );

  YAHOO.util.Dom.setXY( 'otherLoc', pos );

  o.style.visibility = 'visible';
}

var sidebar = new Sidebar( 'weatherHolder' );

</script>

</head>

<%
   boolean isOther = "true".equals( request.getParameter( "isOtherLocation" ) );

   WeatherManager manager = WeatherManager.getInstance();

   String weatherLocation = request.getParameter( "weatherLocation" );
   if ( weatherLocation == null || weatherLocation.length() == 0 ) {
     weatherLocation = manager.getCurrentLocationId();
   }
   
   Vector locations = manager.getLocations();

   WeatherLocation location = null;
   WeatherReport report = null;

   String error = null;
   if ( locations.size() == 0 ) {
     error = "Add some weather locations!";
   }
   else {
     location = manager.getLocationWithReportById( weatherLocation );
     if ( location == null && isOther ) {
       location = manager.getOtherLocationWithReport( weatherLocation );
     }

     if ( location != null ) {
       report = location.getReport();
     }

     if ( report != null && report.hasError() ) {
       error = report.getError();
       location = manager.getCurrentLocation();
       report = location.getReport();
     }
  }

%>

<body style="overflow:hidden; background:#000033; margin:0px; padding:0px;">

<div id="weatherHolder" style="background:#003366; position:relative; width:100%; height:100%; z-index:2;">

<div class="supplementaryNav">
<a class="supnavlink" href="javascript:sidebar.showSidebar( true )">edit locations</a>
</div>

<center>

<div class="weatherMain">

<div id="weatherLoc" class="weatherLocation">
<form id="weatherLocForm" style="position:relative;">
      <select name="weatherLocation" class="weatherLocationSelect" onChange="handleLocationSelect( this )">
        <option value="">Select a location ...</option>
<% if ( isOther && error == null ) { %>
        <option value="other" SELECTED><%= location.getLocationName() %></option>
<% } %>
<% for ( Enumeration e = locations.elements(); e.hasMoreElements(); ) {
     WeatherLocation loc = (WeatherLocation) e.nextElement();
%>
        <option value="<%= loc.getLocationId() %>"<%= loc.equals( location ) ? " SELECTED" : "" %>><%= loc.getLocationName() %></option>
<% } %>
        <option value="other">Other ...</option>
      </select>
</form>
</div>

<% if ( location != null && report != null ) { %>
<table id="wt" cellpadding="0" cellspacing="0" border="0" class="weatherTable">
<tr>
  <td colspan="5" class="currentConditions">
<p class="currentTemp"><%= report.getTemp() %>&deg; (<%= report.getFeelsLikeTemp() %>&deg;)</p>
<span class="currentDescription"><%= report.getWeatherDesc() %></span>
  </td>
</tr>
<tr>
<%
  Iterator days = report.getForecast();
  while ( days.hasNext() ) {
    DailyForecastInfo info = (DailyForecastInfo) days.next();
%>
  <td class="dayname"><%= info.getDayName() %></td>
<% } %>
</tr>
<tr>
<% 
    Iterator forecast = report.getForecast();
    while ( forecast.hasNext() ) {
      DailyForecastInfo info = (DailyForecastInfo) forecast.next();
%>
  <td class="forecast">
    <div class="forecastTemp"><%= info.getHiTemp() %>&deg; / <%= info.getLowTemp() %>&deg;</div>
    <div class="forecastDesc">
      <%= info.getDayWeatherDesc() %><br>
      <%= info.getNightWeatherDesc() %>
    </div>
  </td>
<%  } %>
</tr>
<tr>
  <td colspan="5" class="weatherTime">
<%
  Date lastRefresh = report.getTime();
  TimeDelta td = new TimeDelta( DateFactory.getInstance().getDate().getTime(), lastRefresh.getTime() );
%>
    Last update: <%= td.toTimeString() %>
  </td>
</tr>
</table>
<% } else { %>
<div class="weatherDivBlank"></div>
<% } %>

<% if ( error != null ) { %>
<div class="weatherError">
<% if ( locations.size() == 0 ) { %>
<%= error %>
<% } else { %>
Problem getting weather report for location '<%= weatherLocation %>' (<%= error %>)
<% } %>
</div>
<% } %>

</div>

</center>

<div id="otherLoc" class="otherLocSt">
<form id="otherLocForm">
<input name="weatherLocation" onChange="document.getElementById( 'otherLocForm' ).submit();" id="otherLocation" type="text" size="15" class="otherLocInput">
<input type="hidden" name="isOtherLocation" value="true">
</form>
</div>

<jsp:include page="nav.html" />

</div>

<div id="weatherLocationsEdit" style="width:230px; position:absolute; top:0px; right:0px; z-index:1; padding:10px; color:#ffffff;">

<div style="padding-bottom:15px;">
<table width="100%" cellpadding="0" cellspacing="0" margin="0">
<tr><td class="weatherLocText">weather locations</td><td align="right"><a class="supnavlink" href="javascript:sidebar.showSidebar( false )">hide locations</a></td></tr>
</table>
</div>

<div id="weatherLocations">
<% for ( Enumeration e = locations.elements(); e.hasMoreElements(); ) { 
     WeatherLocation loc = (WeatherLocation) e.nextElement();
%>
<div class="notebookIndexEntry">
<table width="100%" cellpadding="0" cellspacing="0" margin="0">
<tr>
<td class="weatherLocText"><%= loc.getLocationName() %></td>
<td align='right'><a href="javascript:deleteLocation( '<%= loc.getLocationId() %>' )" class="supnavlink">delete</a></td>
</tr>
</table>
</div>
<% } %>

</div>

<div class="notebookIndexEntry">
<table width="100%" cellpadding="0" cellspacing="0" margin="0">
<tr><td colspan="2" align="right">
<div id="addNewLocation"><a class="supnavlink" href="javascript:showNewLocationField()">add new location</a></div>
</td></tr>
</table>
</div>

</div>

</body>

<script>

var addNewPageLink;

function showNewLocationField ()
{
  var t = document.createElement( "input" );
  t.setAttribute( "type", "text" );
  t.setAttribute( "name", "pageName" );
  t.setAttribute( "maxlength", "25" );
  t.setAttribute( "style", "font-size:x-small; width:100%;" );
  t.setAttribute( "onKeyPress", "addNewLocation(event,this)" );

  var c = document.getElementById( "addNewLocation" );
  addNewLocationLink = c.firstChild;
  c.replaceChild( t, c.firstChild );

  var b = document.createElement( "div" );
  b.setAttribute( "class", "cancelNewsSource" );

  var cancelLink = document.createElement( "a" );
  cancelLink.setAttribute( "href", "javascript:cancelAddNewLocation()" );
  cancelLink.setAttribute( "class", "supnavlink" );
  cancelLink.appendChild( document.createTextNode( "cancel" ) );

  b.appendChild( cancelLink );

  c.appendChild( b );

  t.focus();
}

function cancelAddNewLocation ()
{
  var c = document.getElementById( "addNewLocation" );
  while ( c.hasChildNodes() ) { c.removeChild( c.firstChild ); }
  c.appendChild( addNewLocationLink );
}

function addNewLocation( evt, l )
{
  if ( evt.which == 13 ) {
    //alert( "adding new location: " + l.value );

    var surl = 'weather?action=add&id=' + escape( l.value );

    var callback = 
    {
      success : handleAddLocation,
      failure : handleFailure
    };

    YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
  }
}

function handleAddLocation ( obj )
{
  cancelAddNewLocation();

  var doc = obj.responseXML;
  var error = doc.getElementsByTagName( "locations" ).item( 0 ).getAttribute( "errorMessage" );
  if ( error != '' )
  {
    alert( error );
  } else {
    buildLocations( obj );
  }
}

function deleteLocation ( l )
{
  var surl = 'weather?action=delete&id=' + escape( l );

  var callback = 
  {
    success : handleDeleteLocation,
    failure : handleFailure
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function handleDeleteLocation ( obj )
{
  buildLocations( obj );
}

function getLocations ()
{
  var surl = 'weather?action=list';

  var callback = 
  {
    success : buildLocations,
    failure : handleFailure
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function buildLocations ( obj )
{
  var doc = obj.responseXML;

  var locations = doc.getElementsByTagName( "location" );

  //remove locations
  var locDiv = document.getElementById( "weatherLocations" );
  while ( locDiv.hasChildNodes() ) { locDiv.removeChild( locDiv.firstChild ); }

  //clear options
  var locSel = document.forms.weatherLocForm.elements.namedItem( "weatherLocation" );
  var selectedValue = locSel.options.item( locSel.selectedIndex ).value;
  var sl = locSel.options.length;
  for ( var i = 0; i < sl; i++ ) {
    locSel.remove( 0 );
  }

  var el = document.createElement( "OPTION" );
  el.setAttribute( "value", "" );
  el.appendChild( document.createTextNode( "Select a location ..." ) );
  locSel.add( el, null );

  for ( var i = 0; i < locations.length; i++ ) {
    var id = locations.item( i ).getAttribute( "id" );
    var name = locations.item( i ).getAttribute( "name" );

    //add an option
    var el = document.createElement( "OPTION" );
    el.setAttribute( "value", id );
    el.appendChild( document.createTextNode( name ) );
    locSel.add( el, null );

    var d = document.createElement( "DIV" );
    d.setAttribute( "class", "notebookIndexEntry" );

    var t = document.createElement( "TABLE" );
    t.setAttribute( "width", "100%" );
    t.setAttribute( "cellpadding", "0" );
    t.setAttribute( "cellspacing", "0" );
    t.setAttribute( "margin", "0" );
    
    var tr = document.createElement( "TR" );
    var td_name = document.createElement( "TD" );
    td_name.setAttribute( "class", "weatherLocText" );
    td_name.appendChild( document.createTextNode( name ) );
    
    var td_del = document.createElement( "TD" );
    td_del.setAttribute( "align", "right" );
    var del = document.createElement( "A" );
    del.setAttribute( "class", "supnavlink" );
    del.setAttribute( "href", "javascript:deleteLocation( '" + id + "' )" );
    del.appendChild( document.createTextNode( "delete" ) );
    td_del.appendChild( del );

    tr.appendChild( td_name );
    tr.appendChild( td_del );

    t.appendChild( tr );

    d.appendChild( t );

    locDiv.appendChild( d );
  }

  var el = document.createElement( "OPTION" );
  el.setAttribute( "value", "other" );
  el.appendChild( document.createTextNode( "Other ..." ) );
  locSel.add( el, null );

  //select the proper option
  var foundSelected = false;
  for ( var i = 0; i < locSel.options.length; i++ )
  {
    if ( locSel.options.item( i ).value == selectedValue ) {
      locSel.selectedIndex = i;
      foundSelected = true;
      break;
    }
  }
  if ( !foundSelected ) {
    var wt = document.getElementById( "wt" );
    wt.innerHTML = "<div class='weatherDivBlank'></div>";
  }
}

function handleFailure ( obj )
{
  alert( "Problem: " + obj.statusText + " (" + obj.status + ")" ); 
}

</script>

</html>